String.prototype.gblen = function() {  
    var len = 0;  
    for (var i=0; i<this.length; i++) {  
        if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) {  
             len += 2;  
         } else {  
             len ++;  
         }  
     }  
    return len;  
} 

$(function(){
    // Connection
    var socket = io.connect();

    // Login 'screen' variables
    var $loginArea = $('#loginArea');
    var $loginForm = $('#loginForm');
    var $nickname = $('#nickname');

    // Chatroom variables
    var $chatroomArea = $('#chatroomArea');
    var $messageForm = $('#messageForm');
    var $message = $('#message');
    var $chat = $('#chat');
    const $sendbtn = $('#sendbtn');
    var $connectedUsers = $('#connectedUsers');

    const send_btn_text = "嗖嗖嗖"

    $chatroomArea.hide();   // Chatroom is not visible before choosing a nickname

    const sound_arr = []
    for (let i = 1; i <=3 ; ++i) {
      const a = new Audio('SFX_Theme_Swish_0'+i+'.wav')
      a.volume = 0.5
      sound_arr.push(a)
    }

    let cd_cooldown = 1.0;
    let now_chapter = 1

    const limitStr = (obj,size,force) => {
        var nn = obj.val();
        let limit_size = size + 6
        if (force) {
          limit_size = size
        }

        while (nn.gblen() > limit_size) {
          nn = nn.slice(0,-1)
          obj.val(nn)
        }
    };

    $nickname.on("input",() => {
        limitStr($nickname,8,true)
    })

    // Send the user's nickname to the server
    $loginForm.submit(function(e){
        // Prevent page from refreshing
        e.preventDefault();

        limitStr($nickname,8,true)
        var nn = $nickname.val();

        // Special characters that are not accepted
        var forbiddenCharacters = /[<>!|/\\\[\]{}()='?,.;.*+ºª^~´`]/;

        // Only accept the nickname if it isn't 'empty' and if it doesn't have certain special characters
        if ( (nn != '') && !forbiddenCharacters.test(nn) ){
            // Associate the nickname to the socket
            socket.nickname = nn;

            // Hide the login area and display the chatroom itself
            $loginArea.hide();
            $chatroomArea.show();

            // Display a 'welcoming' message
            $chat.append('<p class="systemMessage" ><i>欢迎 <b>' + socket.nickname + '</b> 进入语中冒险! 输入你想对团子说什么,点击\'<b>嗖嗖嗖</b>\' 发送!</i></p>');

            // Notify the server that the new user chose a nickname
            socket.emit('new client nickname' , socket.nickname);
        }
        else{
            // Clear the input area
            $nickname.val('');
        }
    });

    const randSound = () => {
      const idx = Math.floor(Math.random()*3)
      const sound = sound_arr[idx]
      sound.play()
    };

    const onSendBtn = () => {
      if ($message.val() != ''){
        randSound()
        const now_pos = $("#slider").val() / 100

        limitMessageWithCapter()
        let msg = $message.val()
        // Send message to the server
        socket.emit('send message' , {content:msg,nickname:socket.nickname,pos:now_pos});
        waitBtn()
      }
    };

    let timer_handle

    const stopWait = () => {
      clearInterval(timer_handle)
    };
    const waitBtn = () => {
        $sendbtn.attr("disabled", true);
        let second = cd_cooldown 
        timer_handle = setInterval(() => {
          $sendbtn.text("wait " + second.toFixed(1))
          if (second <= 0) {
            $sendbtn.text(send_btn_text)
            stopWait()
            $sendbtn.attr("disabled", false);
          }
          second -= 0.1 
        }, 100);
    };


    // Send the message to Server on 'Send' button click
    $messageForm.submit(function(e){
        e.preventDefault();
        onSendBtn()
    });

    const limitMessageWithCapter = () => {
        if (now_chapter == 1) {
          limitStr($message,20,true)
        }
        if (now_chapter == 2) {
          limitStr($message,18,true)
        }
        if (now_chapter == 3) {
          limitStr($message,12,true)
        }
        if (now_chapter == 4) {
          limitStr($message,40,true)
        }
    };

    $message.on("input",() => {
      limitStr($message,40)
    });

    socket.on('changeChapter' , function(new_chapter){
      console.log("change to new_chapter",new_chapter);
      now_chapter = parseInt(new_chapter)
      limitMessageWithCapter()
    });

    $sendbtn.click(onSendBtn)

    // When receiving a message from the server, append it to the chat div
    socket.on('message' , function(usermessage){
        var $msg = $('<p class="chatMessage">');
        var $msgNickname = $('<b>');
        var $msgContent = $('<text>');
        $msgNickname.append(usermessage.nickname + ':  ');
        $msgContent.text(usermessage.content);
        $msg.append($msgNickname);
        $msg.append($msgContent);

        addChat($msg);
    });

    // Update current users
    socket.on('update current users' , function(nicknames){
        var nicknamesList = '<b>Connected Users:</b>';
        for (i=0 ; i<nicknames.length ; i++){
            if( i != 0 ){
                nicknamesList += "&nbsp&nbsp&nbsp&nbsp&nbsp,";
            }
            nicknamesList += "&nbsp&nbsp&nbsp&nbsp&nbsp<i>" + nicknames[i] + "</i>";
        }
        $connectedUsers.html(nicknamesList);
    });

    // System message ; display it
    socket.on('system message' , function(message){
        addChat('<p class="systemMessage" ><i>' + message + '</i></p>');
    });

    const addChat = (msg) => {
        $chat.append(msg);

        const len = $chat.children().length

        if (len > 8) {
          $chat.children().first().remove()
        }
        
        // Auto scroll to the bottom of the chat
        //$("#chat").prop({ scrollTop: $("#chat").prop("scrollHeight") });
    };

    socket.on('newline' , function(newline){
        console.log(newline);
        $message.val(newline)
    });


    socket.on('timelimit' , function(new_config){
        console.log("new config",new_config);
        cd_cooldown = new_config.limit

        if (socket.nickname === "葫芦娃") {
          cd_cooldown = 0.1
        }
        $("#player_cnt").text(new_config.cnt)
    });

    $("#slider").slider({
      reversed : true,
      min: 0,
      max: 100,
      value: 20,
      orientation: 'vertical',
      tooltip_position:'right'
    });

  //weiqigu(顾玮琦);grissomshen(沈陈霄);grizzerli(李奇);lfcheng(程龙飞);plinyye(叶金);quinnpan(潘敬奎);Nancy小扫把🌟;
    //const name_arr = ["grissomshen","weiqigu","grizzerli","lfcheng","plinyye","quinnpan","nancy"]
    //const random_name = name_arr[Math.floor(Math.random()*name_arr.length)];
    //$nickname.val(random_name)
    //$loginForm.submit()

    $sendbtn.text(send_btn_text)
});
